<?php

namespace addons\mrbs\controller;

use app\common\controller\Api as Base;
use function Composer\Autoload\includeFile;

/**
 * 房间接口
 */
class Api extends Base
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    private $room;

    public function _initialize()
    {
        parent::_initialize();
        $this->edifice    = new \addons\mrbs\model\Edifice;
        $this->room       = new \addons\mrbs\model\Room;
        $this->roomWeeks  = new \addons\mrbs\model\RoomWeeks;
        $this->roomTimes  = new \addons\mrbs\model\RoomTimes;
        $this->order      = new \addons\mrbs\model\Order;
        $this->facilities = new \addons\mrbs\model\Facilities;

    }

    /**
     * 获取大厦列表
     * @return [type] [description]
     */
    public function edifice()
    {
        $year  = $this->request->param('dyearay', date('Y'));
        $month = $this->request->param('month', date('m'));
        $day   = $this->request->param('day', date('d'));
        // 大厦列表
        $edifice = $this->edifice->order('id desc')->select();
        $week    = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        foreach ($edifice as &$value) {
            // 最近七天房间情况
            $dates = [];
            for ($i = 0; $i < 7; $i++) {
                $ids    = $this->room->where('edifice_id', $value['id'])->where('status', 1)->column('id');
                $status = $this->roomWeeks
                    ->where('room_id', 'in', $ids)
                    ->where('week', $i + 1)
                    ->count();
                $time    = strtotime($year . '-' . $month . '-' . $day) + $i * 86400;
                $dates[] = [
                    'day'      => date('j', $time),
                    'week'     => $i + 1,
                    'weekName' => ($day + $i) == date('d') ? '今天' : $week[date('w', $time)],
                    'status'   => $status ? 1 : 0,
                ];
                $value['date'] = $dates;
            }
        }

        return $this->success("查询成功", $edifice);
    }

    /**
     * 获取房间列表
     * @return [type] [description]
     */
    public function room()
    {
        $year       = $this->request->param('year', date('Y'));
        $month      = $this->request->param('month', date('m'));
        $day        = $this->request->param('day', date('d'));
        $edifice_id = $this->request->param('edifice_id');
        $week       = date('w', strtotime($year . '-' . $month . '-' . $day));
        // 查询时间
        $id_arr = $this->roomWeeks->where('week', $week)->select();
        // 获取房间列表
        $rooms = $this->room
            ->with('edifice')
            ->where('room.id', 'in', array_column($id_arr, 'room_id'))
            ->field("room.id,edifice.name,room.title,room.room_type,room.manager_name,room.number")
            ->select();
        foreach ($rooms as &$value) {
            // 查询房间预订情况
            $orders      = $this->order->where('room_id', $value['id'])->where('status', 'neq', -1)->where('starttime', '>', time() - 86400)->field('starttime,hour')->select();
            $order_times = [];
            foreach ($orders as $order) {
                //会议结束时间
                $endtime = $order['starttime'] + $order['hour'] * 3600;
                for ($i = 0; $i <= $order['hour']; $i++) {
                    //当前小时开始时间
                    $hourtime = strtotime(date('Y-m-d H:00:00', $order['starttime'] + $i * 3600));
                    if ($i == 0) {
                        $b = $endtime > ($hourtime + 3600) ? ($hourtime + 3600 - $order['starttime']) / 3600 : $order['hour'];
                    } else {
                        $b = ($endtime - $hourtime) > 3600 ? 1 : ($endtime - $hourtime) / 3600;
                    }

                    $key = date('n-j-G', $hourtime);
                    // 两个时间段在同一小时内交叉时需要相加
                    if (!empty($order_times[$key])) {
                        $order_times[$key] += round($b * 100, 2);
                    } else {
                        $order_times[$key] = round($b * 100, 2);
                    }

                }
            }
            // 获取开放时间
            $times  = $this->roomTimes->field('time,time_stage')->where('room_id', $value['id'])->select();
           // echo $this->roomTimes->getLastSql();
            $_times = [];
            foreach ($times as $time) {
                $key                   = $month . '-' . $day . '-' . $time['time'];
                //array_merge($_times[$time['time']],$time['time_stage']);
               // $_times[$time['time']] = isset($order_times[$key]) ? $order_times[$key] : 0;
                //$stageTime = array();
                //array_push($stageTime,$time['time_stage']);
//                $timeStages = array();
//                if (key_exists($time['time'],$_times)){
//                    array_push($timeStages,$time['time_stage']);
//                    //array_push($_times[$time['time']],$time['time_stage']);
//                }
                //$test = ["1"=>0,""]
                //$timeStages = [$time['time_stage']=>0];

                $_times[$time['time']][] = [$time['time_stage']=>0];
            }

            foreach ($_times as $key => $time){
                $tempTime = array();
                $tempTime["1"] = 1;
                $tempTime["2"] = 1;
                $tempTime["3"] = 1;
                $tempTime["4"] = 1;
                if (key_exists("1",$_times[$key])){
                    $tempTime["1"] = 0;
                }
                if (key_exists("2",$_times[$key])){
                    $tempTime["2"] = 0;
                }
                if (!key_exists("3",$_times[$key])){
                    $tempTime["3"] = 0;
                }
                if (!key_exists("4",$_times[$key])){
                    $tempTime["4"] = 0;
                }
                $_times[$key] = $tempTime;
            }
            //print_r($_times);
            $value['times'] = $_times;
            $value['room_type_str'] = $value['room_type_text'] == 'Room_type 0'?'固定': '临时';
            unset($value['edifice']);
            unset($value['edifice_id']);
            unset($value['floor']);
            unset($value['images']);
            unset($value['status_text']);
            unset($value['Status']);
            unset($value['room_type_text']);
            unset($value['facilities']);
            unset($value['content']);
            unset($value['weigh']);
            unset($value['manager_id']);
            unset($value['status']);
            unset($value['is_verify']);
            unset($value["number"]);
            $value['site'] = $value['title'];
            unset($value['title']);

           // $value['de']
            // 设施列表
//            $value['facilities'] = $this->facilities->where('id', 'in', $value['facilities'])->select();
//            // 图片处理
//            $images = explode(',', $value['images']);
//            foreach ($images as &$image) {
//                $image = cdnurl($image);
//            }
//            $value['images'] = $images;
//            $value['thumb']  = $images[0];
        }
        return $this->success("查询成功", $rooms);
    }

    /**
     * 房间详情
     * @return [type] [description]
     */
    public function info()
    {
        $year  = $this->request->param('year', date('Y'));
        $month = $this->request->param('month', date('m'));
        $day   = $this->request->param('day', date('d'));
        $id    = $this->request->param('id');
        $room  = $this->room->where('id', $id)->find();
        // 查询房间预订情况
        $orders      = $this->order->where('room_id', $room['id'])->where('status', 'neq', -1)->where('starttime', '>', time() - 86400)->field('starttime,endtime')->select();
        $order_times = [];
        foreach ($orders as $order) {
            //每小时分成四份显示
            $step = 15 * 60;
            for ($i = $order['starttime']; $i < $order['endtime']; $i = $i + $step) {
                //获取时间刻钟
                $h = strtotime(date('Y-m-d H:00:00', $i));
                for ($j = 3; $j >= 0; $j--) {
                    if ($i - $h >= $j * $step) {
                        $order_times[] = date('n-j-G', $i) . '-' . $j;
                        break;
                    }
                }
            }
        }
        // 获取开放时间
        $times  = $this->roomTimes->field('time')->where('room_id', $room['id'])->select();
        $_times = [];
        foreach ($times as $time) {
            for ($i = 0; $i < 4; $i++) {
                $_times[$time['time']][] = !in_array($month . '-' . $day . '-' . $time['time'] . '-' . $i, $order_times);
            }
        }
        $room['times'] = $_times;
        // 设施列表
        $room['facilities'] = $this->facilities->where('id', 'in', $room['facilities'])->select();
        // 图片处理
        $images = explode(',', $room['images']);
        foreach ($images as &$image) {
            $image = cdnurl($image);
        }
        $room['images'] = $images;
        $room['thumb']  = $images[0];

        return $this->success("查询成功", $room);
    }

    /**
     * 订单列表
     * @return [type] [description]
     */
    public function order()
    {
        $status = $this->request->param('status', 1);
        $map    = [
            'token' => $this->request->param('token'),
        ];
        if ($status == 1) {
            //待开会
            $map['endtime'] = ['>', strtotime(date('Y-m-d', time()))];
        } elseif ($status == 2) {
            // 历史会议
            $map['endtime'] = ['<', strtotime(date('Y-m-d', time()))];
        }
        $list = $this->order->where($map)->order('starttime desc')->select();
        foreach ($list as &$value) {
            if ($value['room']) {
                $value['room'] = $value['room']->toArray();
            }
        }
        return $this->success('查询成功', $list);
    }

    /**
     * 订单创建接口
     * @return [type] [description]
     */
    public function orderCreate()
    {
        $contact = $this->request->param('contact');
        $room_id = $this->request->param('room_id');
        $title   = $this->request->param('title');
        $people  = $this->request->param('people', 0);
        $date    = $this->request->param('date');
        $token   = $this->request->param('token');
        $hour    = $this->request->param('hour', 1);
        $start   = strtotime($date);
        $end     = strtotime($date) + $hour * 3600;
        // 房间信息
        $room = $this->room->where('id', $room_id)->find();
        if ($room['people'] < $people) {
            return $this->error('超过房间最大容纳人数');
        }
        // 判断该时段是否开放
        for ($i = $start; $i < $end; $i += 3600) {
            // 判断日期是否开放
            $week = date('w', $i);
            $res  = $this->roomWeeks->where('room_id', $room_id)->where('week', $week)->count();
            if (!$res) {
                return $this->error(lang('week')[$week] . '未开放');
            }
            // 判断时间是否开放
            $h   = date('H', $i);
            $res = $this->roomTimes->where('room_id', $room_id)->where('time', $h)->count();
            if (!$res) {
                return $this->error($h . '点未开放');
            }
        }
        // 判断是否有人预定
        $map = [
            'room_id' => $room_id,
            'status'  => ['neq', -1],
        ];
        $res = $this->order->where($map)->where(function ($query) use ($start, $end) {
            // 三种情况，开始时间被占用、结束时间被占用、开始结束时间均被占用
            $query->where('starttime', 'BETWEEN', [$start + 1, $end - 1])->whereOr('endtime', 'BETWEEN', [$start + 1, $end - 1])
                ->whereOr(function ($subQyery) use ($start, $end) {
                    $subQyery->where('starttime', '<=', $start)->where('endtime', '>=', $end);
                });
        })->order('starttime asc')->find();
        if ($res) {
            return $this->error(date('h:i', $res['starttime']) . '至' . date('H:i', $res['endtime']) . '已被占用', "", -1);
        }
        // 是否需要审核
        $status = $room['is_verify'] == 1 ? 0 : 1;
        // 提交订单
        $data = [
            'room_id'    => $room_id,
            'contact'    => $contact,
            'token'      => $token,
            'title'      => $title,
            'hour'       => $hour,
            'starttime'  => $start,
            'endtime'    => $end,
            'people'     => $people,
            'createtime' => time(),
            'status'     => $status,
        ];

        $id = $this->order->insertGetId($data);
        if ($id) {
            return $this->success('提交成功', ['id' => $id]);
        } else {
            return $this->error('提交失败');
        }
    }

}
